package org.niugang.config;

import org.niugang.exception.AuthExceptionEntryPoint;
import org.niugang.exception.CustomAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

/**
 * 
 * Copyright: Copyright (c) 2018 863263957@qq.com
 * 
 * @ClassName: ResourceServerConfigurer.java
 * @Description:资源服务器安全配置
 * @author: niugang
 * @date: 2018年9月14日 下午3:42:11
 */
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfigurer extends ResourceServerConfigurerAdapter {

	
	private static final String DEMO_RESOURCE_ID = "api";
	
	@Autowired
	private CustomAccessDeniedHandler customAccessDeniedHandler;


	@Override
	public void configure(ResourceServerSecurityConfigurer resources) {
		resources.resourceId(DEMO_RESOURCE_ID);
		resources.authenticationEntryPoint(new AuthExceptionEntryPoint());
		resources.accessDeniedHandler(customAccessDeniedHandler);
		resources.tokenStore(jwtTokenStore());
	}

	@Override
	public void configure(HttpSecurity http) throws Exception {
		// 注册和登录是允许的，其他都需要认证
		http.authorizeRequests().antMatchers(HttpMethod.POST, "/userservice/user","/userservice/login").permitAll() 
				.anyRequest().authenticated();
	}

	@Bean
	public TokenStore jwtTokenStore() {
		return new JwtTokenStore(jwtAccessTokenConverter());
	}

	//
	@Bean
	protected JwtAccessTokenConverter jwtAccessTokenConverter() {
		JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
		jwtAccessTokenConverter.setSigningKey("ng123456");
		return jwtAccessTokenConverter;
	}

}
